package com.zdya.combatdocuments.util;

import javax.xml.bind.DatatypeConverter;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class KeyUtil {

    public static PrivateKey getPrivateKey(String keyString) throws NoSuchAlgorithmException, InvalidKeySpecException {
        String[] keys = keyString.split("\n");
        StringBuffer keysb = new StringBuffer();
        for (String k :keys ) {
            if (!k.contains("PRIVATE")) {
                keysb.append(k);
            }
        }
        byte[] encoded = DatatypeConverter.parseBase64Binary(keysb.toString());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        KeyFactory kf = KeyFactory.getInstance("EC");
        PrivateKey key = kf.generatePrivate(keySpec);
        return key;
    }


    public static void main(String[] args) throws InvalidKeySpecException, NoSuchAlgorithmException {
        String aa ="-----BEGIN PRIVATE KEY-----\n" +
                "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgeLlYNI6INxT168Z4\n" +
                "DbJ8QlXFVL0LZaYYwR4bHyMi0jChRANCAARMnSOPESolarldVqTBh6ALLRryKt59\n" +
                "yTiW/ocVUjNKn/MZP0ahAmhy02cB5QfT0Uyx6GBmEvDFmK/Bia1/3UmU\n" +
                "-----END PRIVATE KEY-----\n";
        PrivateKey privateKey = getPrivateKey(aa);
        System.out.println(privateKey.getFormat());
    }
}
